﻿namespace HxMSimulator
{
    using System;
    using System.IO.Ports;

    public class SerialPortWriter : IDisposable
    {
        private const int PortBaudRate = 115200;
        private const Parity PortParity = Parity.None;
        private const StopBits PortStopBits = StopBits.One;
        private const byte PortDataBits = 8;
        private static SerialPortWriter uniqueInstanceOfSerialPortWriter;
        private readonly SerialPort serialPort = new SerialPort();
        
        private SerialPortWriter(string comPortName)
        {
            this.serialPort.PortName = comPortName;
            this.serialPort.BaudRate = PortBaudRate;
            this.serialPort.Parity = PortParity;
            this.serialPort.StopBits = PortStopBits;
            this.serialPort.DataBits = PortDataBits;
        }

        private bool IsConnectedToComPort
        {
            get
            {
                return this.serialPort.IsOpen;
            }
        }

        public static SerialPortWriter GetInstance(string comPortName)
        {
            return uniqueInstanceOfSerialPortWriter ?? (uniqueInstanceOfSerialPortWriter = new SerialPortWriter(comPortName));
        }

        
        public void Dispose()
        {
            if (this.serialPort.IsOpen)
            {
                this.ClosePort();
            }
        }

        public void OpenPort()
        {
            if (this.serialPort.IsOpen)
            {
                this.serialPort.Close();
            }

            this.serialPort.Open();
        }

        public void ClosePort()
        {
            if (this.serialPort.IsOpen)
            {
                this.serialPort.Close();
            }
        }

        public void WriteToSerialPort(byte[] buffer)
        {
            this.serialPort.Write(buffer, 0, buffer.Length);
        } 
    }
}
